@file:JvmName("ImageViewExt")

package com.sea.base.ext.view

import android.app.Activity
import android.widget.ImageView
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.sea.base.R
import com.sea.base.ext.global.colorIntToColorStateList
import com.sea.base.ext.global.isHttp
import com.sea.base.ext.global.postMainSmart

/**
 * @param baseUrl 当不是http开头时加的前缀链接
 * @param url 只支持url
 */
@JvmOverloads
fun ImageView.loadUrl(
    url: String?,
    @DrawableRes resId: Int = R.drawable.base_ic_load_image_fail,
    baseUrl: String? = "",
) {
    if (url.isNullOrEmpty()) {
        setImageResource(resId)
        return
    }

    val fixedUrl = when {
        url.isHttp() || url.startsWith("/storage/") -> {
            url
        }

        else -> {
            baseUrl + url
        }
    }

    innerLoadUrl(this, fixedUrl, resId)
}

private fun innerLoadUrl(iv: ImageView, fixedUrl: String, resId: Int) {
    val context = iv.realContext
    if (context is Activity && context.isFinishing) {
        return
    }
    postMainSmart {
        try {
            //解决第一次加载默认资源会变形的问题
            iv.setImageResource(resId)
            Glide.with(context)
                .load(fixedUrl)
                .diskCacheStrategy(DiskCacheStrategy.ALL) //这个属性会引起第一次加载变形，后续再查询根本原因，已在上方自己设置图片了
                .error(resId)
                .into(iv)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

fun ImageView.setTintColorInt(@ColorInt tintColor: Int) {
    imageTintList = tintColor.colorIntToColorStateList
}